import dictAPI from '@/api/common'
import LocalDict from '../dict/LocalDict'

export default function(dicts, options) {
  const opts = options || {
    valueKey: 'dictCode',
    labelKey: 'dictName'
  }

  return {
    data() {
      return {
        dictLoading: true,
        dictOptions: {}
      }
    },
    created() {
      this.dictLoading = true
      // 若字典以@Local结尾，则从本地获取，否则从远程获取
      const [localDicts, remoteDicts] = dicts.reduce(
        (cfg, cur) => {
          if (/@Local$/.test(cur)) {
            cfg[0].push(cur.replace(/@Local$/, ''))
          } else {
            cfg[1].push(cur)
          }
          return cfg
        },
        [[], []]
      )

      // 设置初始空数组

      // 获取本地字典
      localDicts.forEach(dict => this.$set(this.dictOptions, dict, LocalDict[dict]))

      if (remoteDicts.length === 0) return
      // 获取远程字典
      remoteDicts.forEach(item => this.$set(this.dictOptions, item, []))
      dictAPI.mulFetchPage(remoteDicts).then(res => {
        Object.keys(res.data).forEach(key => {
          const dict = res.data[key]
            .map(item => ({
              value: item[opts.valueKey],
              label: item[opts.labelKey],
              raw: item
            }))
            .sort((a, b) => a.raw.dictSort - b.raw.dictSort)

          this.$set(this.dictOptions, key, dict)
        })
        this.onDictLoaded && this.onDictLoaded()
      }).finally(() => {
        this.dictLoading = false
      })
    },
    methods: {
      getDictText(dictName, value) {
        const dict = this.dictOptions[dictName]
        if (dict) {
          // eslint-disable-next-line eqeqeq
          const target = dict.find(item => item.value == value)?.label
          return target ?? value
        }
        return value
      }
    }
  }
}
